package com.xemxoso.jsouplocal;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.util.Log;
import com.xemxoso.Variables;
import com.xemxoso.model.KetQuaXoSoMienBac;

public final class JsoupLocal {

	private static final String KQXSMB_URL = "http://xoso.wap.vn/ket-qua-xo-so-mien-bac-xstd.html";
	private static final String KQXSMB_DIV_SELECTOR = ".XS";
	private static final String KQXSMB_LEFT_TABLE_SELECTOR = "table";
	// private static final String KQXSMB_RIGHT_TABLE_SELECTOR = "table";
	private static final String KQXSMB_TITLE_SELECTOR = "h2";
	private static final String KQXSMB_ROW_SELECTOR = "tr";
	private static final String KQXSMB_ROW_2_SELECTOR = ".XS tr.LOTO_ngang_1";

	private static final String KQXSMB_LEFT_TABLE_CELL_SELECTOR = "td:not(.XSMB_1)";
	private static final String KQXSMB_RIGHT_TABLE_CELL_SELECTOR = "td:not(.LOTO_1)";

	private JsoupLocal() {

	}

	public static KetQuaXoSoMienBac parseKQXSMB() {
		KetQuaXoSoMienBac result = new KetQuaXoSoMienBac();

		try {
			// Log.d("Jsoup", "Bat dau lay va parse document");
			Connection connect = Jsoup.connect(KQXSMB_URL)
					.timeout(Variables.OUT).ignoreHttpErrors(true);
			Variables.document = connect.get();
			// day nay
			Log.d("document", "doc = "
					+ Variables.document.select("#content").html()); 
			Elements divNgoai2 = Variables.document.select("div");

			for (Element elm : divNgoai2) {
				Log.d("Jsoup1", "div =" + elm.html());

			}

			Element divNgoai = Variables.document.select(KQXSMB_DIV_SELECTOR)
					.first();

			String title = divNgoai.select(KQXSMB_TITLE_SELECTOR).text();
			result.setTitle(title);

			Element tableThuNhat = divNgoai.select(KQXSMB_LEFT_TABLE_SELECTOR)
					.first();

			Elements trTableThuNhat = tableThuNhat.select(KQXSMB_ROW_SELECTOR);

			int giaiOBang1 = 0;
			int viTriOBang1 = 0;
			int n = 0;
			for (Element tr : trTableThuNhat) {
				Elements tdTableThuNhat = tr
						.select(KQXSMB_LEFT_TABLE_CELL_SELECTOR);
				for (Element td : tdTableThuNhat) {
					String maSo = td.text();
					result.setMaSoTrungThuong(giaiOBang1, viTriOBang1, maSo);
					n++;
					viTriOBang1++;
				}
				if (n == result.SO_GIAI[giaiOBang1]) {
					n = 0;
					giaiOBang1++;
				}
			}
			

			Elements trTableThuHai = Variables.document
					.select(KQXSMB_ROW_2_SELECTOR);

			int viTriOBang2 = 0;
			int m = 0;
			for (Element tr : trTableThuHai) {
				Elements tdTableThuHai = tr
						.select(KQXSMB_RIGHT_TABLE_CELL_SELECTOR);
				for (Element td : tdTableThuHai) {
					String duoi = td.text();

					result.setCacSoDaDuoiMaGiai(viTriOBang2, duoi);
					if (m % 2 == 0) {
						viTriOBang2 += 5;
					} else {
						viTriOBang2 -= 4;
					}
					m++;

				}

			}

		} catch (Exception e) {
			e.printStackTrace();

		}
		return result;

	}
}
